﻿using Frame.Core.IServices.Admin;
using Frame.Core.Models;
using Frame.Core.Repository;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Frame.Core.Services.Admin
{
    public class DeptService : BaseService<Depts>, IDeptService
    {
        readonly IRepositoryBase<Depts> _dal;
        readonly IRepositoryBase<Users> _userRepository;
        public DeptService(IRepositoryBase<Depts> dal, IRepositoryBase<Users> userRepository)
        {
            this._dal = dal;
            base.BaseDal = dal;
            _userRepository = userRepository;
        }
        public async Task<List<Depts>> GetDeptsAsync()
        {
            List<Depts> depts = new List<Depts>();
            List<Depts> dbDepts=await _dal.Select.ToListAsync();
            ResolveDeptCollection(depts, dbDepts, 0, 0);

            return depts;
        }

        private  int ResolveDeptCollection(List<Depts>depts,List<Depts> dbDepts, int? parentDeptId, int level)
        {
            int count = 0;
            foreach (var dept in dbDepts.Where(d => d.ParentID == parentDeptId))
            {
                count++;

                depts.Add(dept);
                dept.TreeLevel = level;
                dept.IsTreeLeaf = true;
                dept.Enabled = true;

                level++;
                // 如果这个节点下没有子节点，则这是个终结节点
                int childCount = ResolveDeptCollection(depts,dbDepts, dept.ID, level);
                if (childCount != 0)
                {
                    dept.IsTreeLeaf = false;
                }
                level--;

            }

            return count;
        }
        public async Task<long> GetDeptParentIDCountById(int parentID)
        {
            return await _dal.Select.Where(a => a.ParentID == parentID).CountAsync();
        }
        public async Task<long> GetDeptUsersCountById(int DeptsId)
        {
            return await _userRepository.Select.Where(a => a.DeptID == DeptsId).CountAsync();
        }
    }
}
